import { resolve } from 'path';
import dataJSon from './data.json' assert { type: 'json' };

type DataJsonWithIndex = typeof dataJSon & { [key: string]: any[] };

const config = await Bun.file(resolve(import.meta.dirname, './config.conf')).text()

const filterList = config
  .split('\n')
  .filter(i => !(i.trim() === '') && !i.includes('#'))

function filterEnum(params: DataJsonWithIndex) {
  return Object.keys(params).reduce((acc, key) => {
    if (filterList.includes(key)) {
      acc[key] = params[key]
    }
    return acc
  }, {} as DataJsonWithIndex)
}

function removeParentheses (params: string) {
  return params.replace(/\((.*?)\)|（(.*?)）/, '')
}

function createTemplate(params: DataJsonWithIndex) {
  let template = '';
  const list = filterEnum(params)

  Object.entries(list).forEach(([key, value]: [string, Record<string, string>[]]) => {
    // Skip if value is undefined
    if (!value) return;
    
    template += `
  // ${key}
  ${value.map((item: Record<string, string>) => {
    const [key, value] = Object.entries(item)[0]
    return `${key}: '${removeParentheses(value)}',`
  }).join('\n  ')}
    `
  });
  
  return `
export const adqEnum = {
  ${template}
}
`
}

const res = createTemplate(dataJSon as DataJsonWithIndex)

await Bun.write('./dist/enum/adq.ts', res)